<?php
/**
 * Created by PhpStorm.
 * User: hans
 * Date: 16/6/2
 * Time: 下午5:58.
 */
namespace App\Http\Controllers;

use App\Helpers\SMS;
use Dingo\Api\Exception\StoreResourceFailedException;
use Dingo\Api\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Validator;

/**
 * Class UserController.
 */
class UserController extends BaseController
{
    protected $client;

    protected $sms;

    /**
     * UserController constructor.
     *
     * @param SMS $sms
     */
    public function __construct(SMS $sms)
    {
        $this->client = new Client();
        $this->sms = $sms;
    }

    /**
     * 用户注册.
     *
     * 注册过程分为两步:
     * 1. 证明你不是机器人。提交手机号码、图形验证码、图形验证码ID, 接收短信验证码;
     * 2. 完成注册。提交手机号码、登录密码、短信验证码.
     *
     * @Post("/user/register")
     * @Parameters({
     *     @Parameter("mobile", required=true, description="手机号码,(1)(2)必填"),
     *     @Parameter("captcha", required=true, description="图形验证码,(1)必填"),
     *     @Parameter("captcha_id", required=true, description="图形验证码ID,(1)必填"),
     *     @Parameter("password", required=true, description="登录密码,(2)必填"),
     *     @Parameter("sms_code", required=true, description="短信验证码,(2)必填")
     * })
     *
     *
     * @Transaction({
     *     @Response(200, body={"message":"success"}),
     *     @Response(400, body={"mobile":"手机号码不正确", "password":"密码长度不正确", "captcha":"图形验证码不正确"})
     * })
     *
     * @param Request $request
     *
     * @return mixed
     */
    public function register(Request $request)
    {
        if (!$request->has('sms_code')) {
            //注册第一步,获取短信验证码
            $message = $this->registerStepOne($request);

            return $this->response->array($message);
        }

        //注册第二步,提交数据
        $message = $this->registerStepTwo($request);

        return $this->response->array($message);
    }

    /**
     * 获取手机验证码
     *
     * @param Request $request
     *
     * @return array
     */
    public function registerStepOne($request)
    {
        $rules = [
            'mobile' => 'required|digits:11',
            'captcha' => 'required|validateCaptcha',
            'captcha_id' => 'required',
        ];

        $messages = [
            'mobile.required' => '手机号码不可为空',
            'mobile.digits' => '手机号码格式不正确',
            'captcha.required' => '图形验证码不可为空',
            'captcha_id.required' => '图形验证码ID不可为空',
            'captcha.validate_captcha' => '验证码不正确',
        ];

        if (!env('REGISTER_CAPTCHA_ON', true)) {
            unset($rules['captcha']);
            unset($rules['captcha_id']);
        }

        //图形验证码比对
        Validator::extend('validateCaptcha', function () use ($request) {
            return $this->validateCaptcha($request->input('captcha_id'), $request->input('captcha'));
        });
        $validator = Validator::make($request->all(), $rules, $messages);

        //验证失败
        if ($validator->fails()) {
            throw new StoreResourceFailedException($validator->errors()->first(), $validator->errors());
        }


        //验证通过,发送手机验证码
        return  $this->sms->sendVerificationCode($request->input('mobile'), 'reg');
    }

    /**
     * 注册第二步.
     *
     * @param Request $request
     */
    public function registerStepTwo($request)
    {
        //验证注册数据
        $rules = [
            'mobile' => 'required|digits:11|validateMobile',
            'password' => 'required|min:6',
            'sms_code' => 'required|validateSmsCode',
        ];

        $messages = [
            'mobile.validate_mobile' => '手机号码已经注册过',
            'sms_code.validate_sms_code' => '短信验证码不正确',
            'password.required' => '密码不可为空',
            'password.min' => '密码长度不能少于6位',
        ];

        Validator::extend('validateMobile', function () use ($request) {
            return $this->validateMobile($request->input('mobile'));
        });

        Validator::extend('validateSmsCode', function () use ($request) {

            //dd($this->sms);
            return $this->sms->validate($request->input('mobile'), $request->input('sms_code'), 'reg');
        });


        $validator = Validator::make($request->all(), $rules, $messages);


        //验证失败
        if ($validator->fails()) {
            throw new StoreResourceFailedException($validator->errors()->first(), $validator->errors());
        }

        //验证通过,保存注册信息
        echo 'Registering data is good.';
    }

    /**
     * 检查手机号是否占用.
     *
     * @param $mobile
     *
     * @return bool
     */
    protected function validateMobile($mobile)
    {
        return true;
    }

    /**
     * 检查图形验证码是否正确.
     *
     * //no test
     *
     * @param $captchaId
     * @param $captcha
     *
     * @return bool
     */
    protected function validateCaptcha($captchaId, $captcha)
    {
        $serverCaptcha = app('redis')->get('captcha:'.$captchaId);

        return $serverCaptcha == trim($captcha);
    }
}
